package com.aa.base.log

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import com.adjust.sdk.*
import com.adjust.sdk.imei.AdjustImei
import com.adjust.sdk.oaid.AdjustOaid
import com.aa.base.BaseUtils
import com.aa.base.PlayerCheck
import com.aa.base.event.EventLiveData
import com.aa.base.log.AppLog
import com.aa.base.log.AppsFlyerUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*

/**
 * @author Afra55
 * @date 5/19/21
 * A smile is the best business card.
 * 超强工具箱app token：flvsdk7r94ao
0. 启动事件
app_launch
awj0yi
app_alive
4n8w77
1.激励视频：
reward_should_show
7hm16s
IM_Reward
c518h9
2. 插屏：
interstitial_should_show
xvl6hi
IM_Interstitial
6o9v3i
3. 原生：
native_should_show
kxspsz
IM_Native
e06khh
4. 开屏：
splash_should_show
hq5m4b
IM_Splash
sy0q2v
5. 非全屏插屏
interpage_should_show
jgbwpx
IM_Interpage
jpjvre
 */
object AdjustUtil {

    private const val app_token = "kkw3z8mxvocg"

    private const val ad_lock_screen_real_show = "azife5"
    private const val ad_lock_screen_should_show = "w89ssk"
    private const val app_alive = "ysxyp8"
    private const val app_launch = "5u3fyf"
    private const val conversion_non_organic = "v38mfx"
    private const val function_use = "nnbhcv"
    private const val IM_Interpage = "f92zys"
    private const val IM_Interstitial = "gks5d9"
    private const val IM_Reward = "d5w7o5"
    private const val IM_Splash = "1jzivc"
    private const val interpage_should_show = "i24y0e"
    private const val interstitial_should_show = "u9rkpn"
    private const val real_retention_rate = "21zvzb"
    private const val retention_rate = "18ealq"
    private const val reward_should_show = "xhuoqa"
    private const val splash_should_show = "ohf8lo"

    private const val keeplive_check_1 = "t6g2gs"
    private const val keeplive_check_2 = "ld6i2j"
    private const val keeplive_check_3 = "yfjcil"
    private const val keeplive_check_4 = "eud5mm"
    private const val keeplive_check_5 = "yqmopa"

    private const val native_should_show = "jtwltr"
    private const val IM_Native = "pbr8xz"

    private const val ad_show_10 = "yz3uvy"
    private const val ad_show_15 = "xggk8m"
    private const val ad_show_20 = "rmn4wj"
    private const val ad_show_5 = "jesjuf"

    private val adjustLifecycleCallbacks by lazy {
        AdjustLifecycleCallbacks()
    }

    fun init(context: Application, nonOrganic: (String) -> Unit) {
        if (PlayerCheck.isNoLimit()) {
        }
        AdjustImei.readImei()
        AdjustOaid.readOaid()
        val debugMode = PlayerCheck.isDebugMode
        val config = AdjustConfig(
            context,
            app_token,
            if (debugMode) AdjustConfig.ENVIRONMENT_SANDBOX else AdjustConfig.ENVIRONMENT_PRODUCTION
        )
        config.setSendInBackground(true)
        if (debugMode) {
            config.setLogLevel(LogLevel.VERBOSE)
        }
        config.setOnAttributionChangedListener {
            // trackerToken 目前归因的跟踪码字符串。
            // trackerName 目前归因的跟踪链接名称字符串。
            // network 目前归因的渠道分组层字符串。
            // campaign 目前归因的推广分组层字符串。
            // adgroup 目前归因的广告组分组层字符串。
            // creative 目前归因的素材分组层字符串。
            // clickLabel 目前归因的点击标签字符串。
            // adid Adjust 设备标识符字符串。
            // costType 成本类型字符串。
            // costAmount 成本金额。
            // costCurrency 成本币种字符串。
            // {"tracker_token":"li84d5y","tracker_name":"Organic","network":"Organic"}}
            if (PlayerCheck.context == null) {
                PlayerCheck.context = context
            }
            it.trackerName?.let { trackName ->
                AppLog.i("trackName=$trackName", "Adjust")
                if (trackName.isNotEmpty() && trackName != "Organic" && trackName != "organic") {
                    PlayerCheck.af_status = trackName.toLowerCase(Locale.getDefault())
                    AppsFlyerUtils.trackEvent(context, "conversion_$trackName")
                    trackEvent(conversion_non_organic)
                    GlobalScope.launch(Dispatchers.Main) {
                        if (PlayerCheck.context == null) {
                            PlayerCheck.context = context
                        }
                        try {
                            PlayerCheck.af_status =
                                trackName.toLowerCase(Locale.getDefault())
                        } catch (e: Exception) {
                        }
                        try {
                            nonOrganic.invoke(trackName)
                        } catch (e: Exception) {
                        }
                        try {
                            EventLiveData.sendEvent("af_status", trackName)
                        } catch (e: Exception) {
                        }
                    }
                }
            }

        }
        Adjust.onCreate(config)


        context.registerActivityLifecycleCallbacks(adjustLifecycleCallbacks)
    }

    /**
     * 应用启动
     */
    fun trackAppLaunch() {
        trackEvent(app_launch)
    }

    /**
     * App 保活事件
     */
    fun trackAppAlive() {
        trackEvent(app_alive)
    }

    /**
     * 激励视频应该展示
     */
    fun trackAdRewardShouldShow( from:String, network:String) {
        trackEvent(reward_should_show)
        TAUtils.trackAdRewardShouldShow(from, network)
    }

    /**
     * 激励视频实际展示
     */
    fun trackAdRewardRealShow( from:String, network:String) {
        trackEvent(IM_Reward)
        TAUtils.trackAdRewardRealShow(from, network)
    }

    /**
     * 插屏应该展示
     */
    fun trackAdInterstitialShouldShow( from:String, network:String) {
        trackEvent(interstitial_should_show)
        TAUtils.trackAdInterstitialShouldShow(from, network)
    }

    /**
     * 插屏实际展示
     */
    fun trackAdInterstitialRealShow( from:String, network:String) {
        trackEvent(IM_Interstitial)
        TAUtils.trackAdInterstitialRealShow(from, network)
    }

    /**
     * 原生广告应该展示
     */
    fun trackAdNativeShouldShow( from:String, network:String) {
        trackEvent(native_should_show)
        TAUtils.trackAdNativeShouldShow(from, network)
    }

    /**
     * 原生广告实际展示
     */
    fun trackAdNativeRealShow( from:String, network:String) {
        trackEvent(IM_Native)
        TAUtils.trackAdNativeRealShow(from, network)
    }

    /**
     * 开屏广告应该展示
     */
    fun trackAdSplashShouldShow( from:String, network:String) {
        trackEvent(splash_should_show)
        TAUtils.trackAdSplashShouldShow(from, network)
    }

    /**
     * 开屏广告实际展示
     */
    fun trackAdSplashRealShow( from:String, network:String) {
        trackEvent(IM_Splash)
        TAUtils.trackAdSplashRealShow(from, network)
    }

    /**
     * 半屏幕插屏应该展示
     */
    fun trackAdInterPageShouldShow( from:String, network:String) {
        trackEvent(interpage_should_show)
        TAUtils.trackAdInterPageShouldShow(from, network)
    }

    /**
     * 半屏幕插屏实际展示
     */
    fun trackAdInterPageRealShow( from:String, network:String) {
        trackEvent(IM_Interpage)
        TAUtils.trackAdInterPageRealShow(from, network)
    }

    fun trackAdLockScreenShouldShow( from:String, network:String) {
        trackEvent(ad_lock_screen_should_show)
        TAUtils.trackAdScreenShouldShow(from, network)
    }

    fun trackAdLockScreenRealShow( from:String, network:String) {
        trackEvent(ad_lock_screen_real_show)
        TAUtils.trackAdScreenRealShow(from, network)
    }

    fun trackFunctionUse() {
        trackEvent(function_use)
    }
    fun trackAdBanner( from:String, network:String) {
        TAUtils.trackAdBanner(from, network)
    }

    fun trackInstallLive(context: Context){
        val sp = context.getSharedPreferences("install_live", Context.MODE_PRIVATE)

        val firstInstallTime = BaseUtils.getFirstInstallTime(context)
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - firstInstallTime > 30 * 60 * 1000) {
            val check1 = sp.getBoolean("check1", false)
            if (!check1) {
                trackEvent(keeplive_check_1)
                sp.edit().putBoolean("check1", true).apply()
            }
        }
        if (currentTimeMillis - firstInstallTime > 60 * 60 * 1000) {
            val check2 = sp.getBoolean("check2", false)
            if (!check2) {
                trackEvent(keeplive_check_2)
                sp.edit().putBoolean("check2", true).apply()
            }
        }

        if (currentTimeMillis - firstInstallTime > 90 * 60 * 1000) {
            val check3 = sp.getBoolean("check3", false)
            if (!check3) {
                trackEvent(keeplive_check_3)
                sp.edit().putBoolean("check3", true).apply()
            }
        }

        if (currentTimeMillis - firstInstallTime > 120 * 60 * 1000) {
            val check4 = sp.getBoolean("check4", false)
            if (!check4) {
                trackEvent(keeplive_check_4)
                sp.edit().putBoolean("check4", true).apply()
            }
        }

        if (currentTimeMillis - firstInstallTime > 150 * 60 * 1000) {
            val check5 = sp.getBoolean("check5", false)
            if (!check5) {
                trackEvent(keeplive_check_5)
                sp.edit().putBoolean("check5", true).apply()
            }
        }
    }
    fun trackRetentionRate(context: Context) {
        try {
            Adjust.trackEvent(AdjustEvent(retention_rate))
        } catch (e: Exception) {
        }
    }

    fun trackRealRetentionRate(context: Context) {
        try {
            Adjust.trackEvent(AdjustEvent(real_retention_rate))
        } catch (e: Exception) {
        }
    }


    fun trackEvent(eventToken: String) {
        try {
            Adjust.trackEvent(AdjustEvent(eventToken))
        } catch (e: Exception) {
        }
    }

    class AdjustLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        override fun onActivityPaused(activity: Activity) {
            Adjust.onPause()
        }

        override fun onActivityStarted(activity: Activity) {

        }

        override fun onActivityDestroyed(activity: Activity) {

        }

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

        }

        override fun onActivityStopped(activity: Activity) {

        }

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

        }

        override fun onActivityResumed(activity: Activity) {
            Adjust.onResume()
        }

    }
    fun trackAdShow5() {
        trackEvent(ad_show_5)
    }

    fun trackAdShow10() {
        trackEvent(ad_show_10)
    }
    fun trackAdShow15() {
        trackEvent(ad_show_15)
    }
    fun trackAdShow20() {
        trackEvent(ad_show_20)
    }
    fun trackAdShowTimes(context: Context) {
        val sp = context.getSharedPreferences("ad_show_count", Context.MODE_PRIVATE)
        var count = sp.getInt("count", 0)
        count += 1
        if (count > 22) {
            return
        }
        if (count >= 5) {
            val b5 = sp.getBoolean("b5", false)
            if (!b5) {
                trackAdShow5()
                TAUtils.trackShowEvent("ad_show_5")
                sp.edit().putBoolean("b5", true).apply()
            }
        }
        if (count >= 10) {
            val b5 = sp.getBoolean("b10", false)
            if (!b5) {
                trackAdShow10()
                TAUtils.trackShowEvent("ad_show_10")
                sp.edit().putBoolean("b10", true).apply()
            }
        }
        if (count >= 15) {
            val b5 = sp.getBoolean("b15", false)
            if (!b5) {
                trackAdShow15()
                TAUtils.trackShowEvent("ad_show_15")
                sp.edit().putBoolean("b15", true).apply()
            }
        }
        if (count >= 20) {
            val b5 = sp.getBoolean("b20", false)
            if (!b5) {
                trackAdShow20()
                TAUtils.trackShowEvent("ad_show_20")
                sp.edit().putBoolean("b20", true).apply()
            }
        }
        sp.edit().putInt("count", count).apply()
    }

}